package com.tc.gateway.tunnel;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public class Tunnel extends Thread{
	TcpTunnelServer server;
	OutputStream out;
	Socket socket;
	
	public Tunnel(OutputStream out, Socket socket,TcpTunnelServer s) {
		super();
		this.out = out;
		this.socket = socket;
		this.server = s;
	}

	@Override
	public void run() {
		byte buffer[] = new byte[256];
		super.run();
		try {
			while(true){
				
				int l = socket.getInputStream().read(buffer);
				out.write(buffer, 0, l);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			server.tunnels.remove(this);
		}
	}

	public void write(byte[] buffer, int offset, int count){
		try {
			socket.getOutputStream().write(buffer, offset, count);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("remove tunnel!remained:" + server.tunnels.size());
			
			server.tunnels.remove(this);
		}
	}

	@Override
	public void interrupt() {
		// TODO Auto-generated method stub
		super.interrupt();
		try {
			socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
